package it.bit.jlightqueryer.gui;

import it.bit.jlightqueryer.Start;
import it.bit.jlightqueryer.bl.Engine;
import it.bit.jlightqueryer.bl.ResultSetResult;
import it.bit.jlightqueryer.bl.U;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.sql.SQLException;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;

/**
 * Visual class of main window to query the database
 * @author PerezDeQueya80
 */
public class FrMain extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JPanel panNorth = null;
	private JLabel lblInfo = null;
	private JToggleButton btnAutoCommit = null;
	private JSplitPane splitMan = null;
	private JButton btnQuery = null;
	private JButton btnExecute = null;
	private JScrollPane spnSQL = null;
	private JTabbedPane tpnResult = null;
	private JScrollPane spnResultQuery = null;
	private JTable tableResultQuery = null;
	private JScrollPane spnResultText = null;
	private JTextArea txtResultText = null;
	private JLabel lblMaxRows = null;
	private JTextField txtMaxRows = null;
	private JButton btnCommit = null;
	private JButton btnRollback = null;
	private JTextArea txtSQL = null;

	/**
	 * This is the default constructor
	 */
	public FrMain() {
		super();
		initialize();

		try {
			Engine.getConnection().getConnection().setAutoCommit(getBtnAutoCommit().isSelected());
			setTitle();
		} catch (SQLException e) {
			setExecuteText(U.stack2string(e));
		}
	}

	private void setTitle() throws SQLException {
		setTitle("JLightQueryer ver."+Start.VERSION+" - "+Engine.getConnection().toString());
		lblInfo.setText(Engine.getConnection().toString());
	}

	public void setVisible(boolean b) {
		if (b)
			U.setLocationRelativeTo(this, null);
		super.setVisible(b);
	}

	public static void main(String[] args) {
		String jvmVer = System.getProperty("java.version");
		if ("1.5".compareTo(jvmVer)<=0)
	    try {
	    	if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1) {
		    	UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
	    	}
	    	else {
		    	System.out.println(UIManager.getCrossPlatformLookAndFeelClassName());
	    	}
	    } catch (Exception e) {
			e.printStackTrace();
	    }

		FrMain fr = new FrMain();
		fr.setVisible(true);
	}

	/**
	 * @return the sql to execute. If selected text is null, return all text in JTextField
	 */
	protected String getSql() {
		String sql = getTxtSQL().getSelectedText();
		if (sql == null || sql.length()<1) {
			return getTxtSQL().getText();
		}
		else
			return sql;
	}

	public void query() {
		try {
			String sql = getSql();
			ResultSetResult rsr = Engine.query(sql, Integer.parseInt(getTxtMaxRows().getText()));
			DefaultTableModel dataModel = new DefaultTableModel(rsr.getDataAsArrays(), rsr.headers) {
				private static final long serialVersionUID = 4402214220447794604L;
				public boolean isCellEditable(int row, int column) {
					return false;
				}
			};
			getTableResultQuery().setModel(dataModel);
			U.adjustColumns(getTableResultQuery());
			getTpnResult().setSelectedComponent(getSpnResultQuery());
		} catch (Exception e) {
			setExecuteText(U.stack2string(e));
		}
	}

	public void execute() {
		try {
			String sql = getSql();
			int i = Engine.execute(sql);
			setExecuteText("execution result: "+i);
		} catch (Exception e) {
			setExecuteText(U.stack2string(e));
		}
	}

	public void setExecuteText(String s) {
		getTxtResultText().setText(s);
		getTxtResultText().setCaretPosition(0);
		getTpnResult().setSelectedComponent(getSpnResultText());
	}

	/**
	 * This method initializes this
	 *
	 * @return void
	 */
	private void initialize() {
		this.setSize(654, 478);
		this.setBackground(new Color(240, 255, 255));
		this.setContentPane(getJContentPane());
		this.setTitle("JLightQueryer");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowOpened(java.awt.event.WindowEvent e) {
				getTxtSQL().requestFocus();
			}
			public void windowClosed(WindowEvent e) {
				try {
					Engine.getConnection().closeConnection();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		});
	}

	/**
	 * This method initializes jContentPane
	 *
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.setOpaque(true);
			jContentPane.setBackground(new Color(240, 255, 255));
			jContentPane.add(getPanNorth(), BorderLayout.NORTH);
			jContentPane.add(getSplitMan(), BorderLayout.CENTER);
		}
		return jContentPane;
	}

	/**
	 * This method initializes panNorth
	 *
	 * @return javax.swing.JPanel
	 */
	private JPanel getPanNorth() {
		if (panNorth == null) {
			GridBagConstraints gridBagConstraints7 = new GridBagConstraints();
			gridBagConstraints7.gridx = 7;
			gridBagConstraints7.gridy = 0;
			GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
			gridBagConstraints6.gridx = 6;
			gridBagConstraints6.gridy = 0;
			GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
			gridBagConstraints5.gridy = 0;
			gridBagConstraints5.gridx = 2;
			GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
			gridBagConstraints4.gridx = 1;
			gridBagConstraints4.insets = new Insets(0, 0, 0, 2);
			gridBagConstraints4.gridy = 0;
			lblMaxRows = new JLabel();
			lblMaxRows.setText("max rows:");
			GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
			gridBagConstraints3.gridx = 4;
			gridBagConstraints3.gridy = 0;
			GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
			gridBagConstraints2.gridx = 3;
			gridBagConstraints2.gridy = 0;
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.insets = new Insets(0, 5, 0, 5);
			gridBagConstraints1.gridy = 0;
			gridBagConstraints1.weightx = 1.0D;
			gridBagConstraints1.anchor = GridBagConstraints.WEST;
			gridBagConstraints1.gridx = 0;
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.gridx = 5;
			gridBagConstraints.gridy = 0;
			lblInfo = new JLabel();
			lblInfo.setText("user@server");
			panNorth = new JPanel();
			panNorth.setLayout(new GridBagLayout());
			panNorth.setOpaque(false);
			panNorth.add(lblInfo, gridBagConstraints1);
			panNorth.add(getBtnAutoCommit(), gridBagConstraints);
			panNorth.add(getBtnQuery(), gridBagConstraints2);
			panNorth.add(getBtnExecute(), gridBagConstraints3);
			panNorth.add(lblMaxRows, gridBagConstraints4);
			panNorth.add(getTxtMaxRows(), gridBagConstraints5);
			panNorth.add(getBtnCommit(), gridBagConstraints6);
			panNorth.add(getBtnRollback(), gridBagConstraints7);
		}
		return panNorth;
	}

	/**
	 * This method initializes btnAutoCommit
	 *
	 * @return javax.swing.JToggleButton
	 */
	private JToggleButton getBtnAutoCommit() {
		if (btnAutoCommit == null) {
			btnAutoCommit = new JToggleButton();
			btnAutoCommit.setIcon(new ImageIcon(Start.getImageResource("autocommit.gif")));
			btnAutoCommit.setOpaque(false);
			btnAutoCommit.setToolTipText("Set autocommit");
			btnAutoCommit.setMargin(new Insets(0, 0, 0, 0));
			btnAutoCommit.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
				}
			});
			btnAutoCommit.addItemListener(new java.awt.event.ItemListener() {
				public void itemStateChanged(java.awt.event.ItemEvent e) {
					try {
						Engine.getConnection().getConnection().setAutoCommit(btnAutoCommit.isSelected());
						getTxtSQL().requestFocus();
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
			});
			btnAutoCommit.addChangeListener(new javax.swing.event.ChangeListener() {
				public void stateChanged(javax.swing.event.ChangeEvent e) {
				}
			});
		}
		return btnAutoCommit;
	}

	/**
	 * This method initializes splitMan
	 *
	 * @return javax.swing.JSplitPane
	 */
	private JSplitPane getSplitMan() {
		if (splitMan == null) {
			splitMan = new JSplitPane();
			splitMan.setOrientation(JSplitPane.VERTICAL_SPLIT);
			splitMan.setOneTouchExpandable(true);
			splitMan.setDividerLocation(150);
			splitMan.setOpaque(false);
			splitMan.setTopComponent(getSpnSQL());
			splitMan.setBottomComponent(getTpnResult());
			splitMan.setDividerSize(8);
		}
		return splitMan;
	}

	/**
	 * This method initializes btnQuery
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getBtnQuery() {
		if (btnQuery == null) {
			btnQuery = new JButton();
			btnQuery.setMargin(new Insets(0, 0, 0, 0));
			btnQuery.setToolTipText("Query the selected text");
			btnQuery.setMnemonic(KeyEvent.VK_Q);
			btnQuery.setOpaque(false);
			btnQuery.setIcon(new ImageIcon(Start.getImageResource("query.gif")));
			btnQuery.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					query();
					getTxtSQL().requestFocus();
				}
			});
		}
		return btnQuery;
	}

	/**
	 * This method initializes btnExecute
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getBtnExecute() {
		if (btnExecute == null) {
			btnExecute = new JButton();
			btnExecute.setMargin(new Insets(0, 0, 0, 0));
			btnExecute.setMnemonic(KeyEvent.VK_X);
			btnExecute.setToolTipText("Execute the selected text");
			btnExecute.setOpaque(false);
			btnExecute.setIcon(new ImageIcon(Start.getImageResource("execute.gif")));
			btnExecute.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					execute();
					getTxtSQL().requestFocus();
				}
			});
		}
		return btnExecute;
	}

	/**
	 * This method initializes spnSQL
	 *
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getSpnSQL() {
		if (spnSQL == null) {
			spnSQL = new JScrollPane();
			spnSQL.setViewportView(getTxtSQL());
		}
		return spnSQL;
	}

	/**
	 * This method initializes tpnResult
	 *
	 * @return javax.swing.JTabbedPane
	 */
	private JTabbedPane getTpnResult() {
		if (tpnResult == null) {
			tpnResult = new JTabbedPane();
			tpnResult.addTab("Table result", null, getSpnResultQuery(), null);
			tpnResult.addTab("Text result", null, getSpnResultText(), null);
		}
		return tpnResult;
	}

	/**
	 * This method initializes spnResultQuery
	 *
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getSpnResultQuery() {
		if (spnResultQuery == null) {
			spnResultQuery = new JScrollPane();
			spnResultQuery.setViewportView(getTableResultQuery());
		}
		return spnResultQuery;
	}

	/**
	 * This method initializes tableResultQuery
	 *
	 * @return javax.swing.JTable
	 */
	private JTable getTableResultQuery() {
		if (tableResultQuery == null) {
			tableResultQuery = new JTable();
			tableResultQuery.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		}
		return tableResultQuery;
	}

	/**
	 * This method initializes spnResultText
	 *
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getSpnResultText() {
		if (spnResultText == null) {
			spnResultText = new JScrollPane();
			spnResultText.setViewportView(getTxtResultText());
		}
		return spnResultText;
	}

	/**
	 * This method initializes txtResultText
	 *
	 * @return javax.swing.JTextArea
	 */
	private JTextArea getTxtResultText() {
		if (txtResultText == null) {
			txtResultText = new JTextArea();
			txtResultText.setFont(new Font("Monospaced", Font.PLAIN, 12));
			txtResultText.setLineWrap(true);
		}
		return txtResultText;
	}

	/**
	 * This method initializes txtMaxRows
	 *
	 * @return javax.swing.JTextField
	 */
	private JTextField getTxtMaxRows() {
		if (txtMaxRows == null) {
			txtMaxRows = new JTextField();
			txtMaxRows.setColumns(3);
			txtMaxRows.setToolTipText("Max rows to query. Put 0 to give all rows");
			txtMaxRows.setText("100");
		}
		return txtMaxRows;
	}

	/**
	 * This method initializes btnCommit
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getBtnCommit() {
		if (btnCommit == null) {
			btnCommit = new JButton();
			btnCommit.setMargin(new Insets(0, 0, 0, 0));
			btnCommit.setOpaque(false);
			btnCommit.setToolTipText("Commit transaction");
			btnCommit.setIcon(new ImageIcon(Start.getImageResource("commit.gif")));
			btnCommit.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					try {
						Engine.getConnection().commit();
						getTxtSQL().requestFocus();
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
			});
		}
		return btnCommit;
	}

	/**
	 * This method initializes btnRollback
	 *
	 * @return javax.swing.JButton
	 */
	private JButton getBtnRollback() {
		if (btnRollback == null) {
			btnRollback = new JButton();
			btnRollback.setMargin(new Insets(0, 0, 0, 0));
			btnRollback.setOpaque(false);
			btnRollback.setToolTipText("Rollback transaction");
			btnRollback.setIcon(new ImageIcon(Start.getImageResource("rollback.gif")));
			btnRollback.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					try {
						Engine.getConnection().rollback();
						getTxtSQL().requestFocus();
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
			});
		}
		return btnRollback;
	}

	/**
	 * This method initializes txtSQL
	 *
	 * @return javax.swing.JTextArea
	 */
	private JTextArea getTxtSQL() {
		if (txtSQL == null) {
			txtSQL = new JTextArea();
		}
		return txtSQL;
	}

}  //  @jve:decl-index=0:visual-constraint="10,10"
